import 'dart:isolate';
import 'dart:io';
import 'dart:convert';
import 'dart:async'; 
const String filename = 'with_keys.json';
void main() async {
  //https://dart.cn/language/isolates/#running-an-existing-method-in-a-new-isolate
  // 读取数据
  final jsonData = await Isolate.run(_readAndParseJson);
  print(jsonData);
  // 使用数据
  print('Number of JSON keys: ${jsonData.length}');

   
  // 打印JSON键的数量
  print('Number of JSON keys: ${jsonData.length}');

//https://dart.cn/language/isolates/#robust-ports-example/#step-1---#step-6
  final worker = await Worker.spawn();
  print(await worker.parseJson('{"key":"value"}'));
  print(await worker.parseJson('"banana"'));
  print(await worker.parseJson('[true, false, null, 1, "string"]'));
  print(
    await Future.wait([worker.parseJson('"yes"'), worker.parseJson('"no"')]),
  );
  worker.close();
}

class Worker {
  final SendPort _commands;
  final ReceivePort _responses;
  final Map<int, Completer<Object?>> _activeRequests = {};
  int _idCounter = 0;
  bool _closed = false;

  Future<Object?> parseJson(String message) async {
    if (_closed) throw StateError('Closed');
    final completer = Completer<Object?>.sync();
    final id = _idCounter++;
    _activeRequests[id] = completer;
    _commands.send((id, message));
    return await completer.future;
  }

  static Future<Worker> spawn() async {
    // Create a receive port and add its initial message handler
    final initPort = RawReceivePort();
    final connection = Completer<(ReceivePort, SendPort)>.sync();
    initPort.handler = (initialMessage) {
      final commandPort = initialMessage as SendPort;
      connection.complete((
        ReceivePort.fromRawReceivePort(initPort),
        commandPort,
      ));
    };

    // Spawn the isolate.
    try {
      await Isolate.spawn(_startRemoteIsolate, (initPort.sendPort));
    } on Object {
      initPort.close();
      rethrow;
    }

    final (ReceivePort receivePort, SendPort sendPort) =
        await connection.future;

    return Worker._(receivePort, sendPort);
  }

  Worker._(this._responses, this._commands) {
    _responses.listen(_handleResponsesFromIsolate);
  }

  void _handleResponsesFromIsolate(dynamic message) {
    final (int id, Object? response) = message as (int, Object?);
    final completer = _activeRequests.remove(id)!;

    if (response is RemoteError) {
      completer.completeError(response);
    } else {
      completer.complete(response);
    }

    if (_closed && _activeRequests.isEmpty) _responses.close();
  }

  static void _handleCommandsToIsolate(
    ReceivePort receivePort,
    SendPort sendPort,
  ) {
    receivePort.listen((message) {
      if (message == 'shutdown') {
        receivePort.close();
        return;
      }
      final (int id, String jsonText) = message as (int, String);
      try {
        final jsonData = jsonDecode(jsonText);
        sendPort.send((id, jsonData));
      } catch (e) {
        sendPort.send((id, RemoteError(e.toString(), '')));
      }
    });
  }

  static void _startRemoteIsolate(SendPort sendPort) {
    final receivePort = ReceivePort();
    sendPort.send(receivePort.sendPort);
    _handleCommandsToIsolate(receivePort, sendPort);
  }

  void close() {
    if (!_closed) {
      _closed = true;
      _commands.send('shutdown');
      if (_activeRequests.isEmpty) _responses.close();
      print('--- port closed --- ');
    }
  }

  
}


// 这是一个异步函数，用于读取和解析JSON文件
Future<Map<String, dynamic>> _readAndParseJson() async {
  try {
    // 读取文件内容
    final fileData = await File(filename).readAsString();
    
    // 解析JSON数据
    final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
    
    // 返回解析后的JSON数据
    return jsonData;
  } catch (e) {
    // 处理可能的错误，例如文件不存在或JSON解析失败
    print('Error reading or parsing JSON: $e');
    return {}; // 返回一个空的Map作为默认值
  }
}
//https://dart.cn/language/isolates/#running-an-existing-method-in-a-new-isolate
Future<Map<String, dynamic>> _readAndParseJsons() async {
  final fileData = await File(filename).readAsString();
  final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
  return jsonData;
}

// 定义JSON文件名
const String filename1 = 'with_keys.json';


//https://dart.cn/language/isolates/#basic-ports-example
class Workerer {
  ReceivePort _receivePort = ReceivePort();
  SendPort? _sendPort;

  Future<void> spawn() async {
    _receivePort.listen(_handleResponsesFromIsolate);
    await Isolate.spawn(_startRemoteIsolate, _receivePort.sendPort);
    _sendPort = await _receivePort.first;
  }

  void _handleResponsesFromIsolate(dynamic message) {
    if (message is Map<String, dynamic>) {
      print('Received JSON: $message');
    } else {
      print('Received message: $message');
    }
  }

  static void _startRemoteIsolate(SendPort port) {
    final receivePort = ReceivePort();
    port.send(receivePort.sendPort);

    receivePort.listen((message) async {
      if (message is String) {
        final jsonData = await _readAndParseJson(message);
        port.send(jsonData);
      }
    });
  }

  static Future<Map<String, dynamic>> _readAndParseJson(String filename) async {
    final fileData = await File(filename).readAsString();
    final jsonData = jsonDecode(fileData) as Map<String, dynamic>;
    return jsonData;
  }

  Future<void> parseJson(String filename) async {
    if (_sendPort != null) {
      _sendPort?.send(filename);
    } else {
      throw Exception('Worker isolate not spawned');
    }
  }
}



//https://dart.cn/language/isolates/#step-3-spawn-a-worker-isolate-with-isolate-spawn to#step-5
class Workers {
  late SendPort _sendPort;
  final _receivePort = ReceivePort();
  Completer<void>? _isolateSetupCompleter;

  Future<void> spawn() async {
    _isolateSetupCompleter = Completer<void>();
    await Isolate.spawn(_startRemoteIsolate, _receivePort.sendPort);
    _receivePort.listen(_handleResponsesFromIsolate);
    await _isolateSetupCompleter!.future; // 等待 Isolate 设置完成
  }

  void _handleResponsesFromIsolate(dynamic message) {
    if (message is SendPort) {
      // 保存 Isolate 的 SendPort
      _sendPort = message;
      _isolateSetupCompleter?.complete(); // 完成 Completer
    } else {
      // 处理从 Isolate 返回的数据
      print('Received from isolate: $message');
    }
  }

  static void _startRemoteIsolate(SendPort port) {
    final receivePort = ReceivePort();
    port.send(receivePort.sendPort);

    receivePort.listen((dynamic message) async {
      if (message is String) {
        final transformed = jsonDecode(message);
        port.send(transformed);
      }
    });
  }

  Future<void> parseJson(String message) async {
    await _isolateSetupCompleter!.future; // 确保 Isolate 已经设置完成
    _sendPort.send(message);
  }
}
















